package annotation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

/**
 * 注解测试
 */
public class AnnotationTest {
    public static void main(String[] args) throws ClassNotFoundException {
//        Serializable
        Set s = new HashSet<String>();
        test2();
    }

    public static void test1() throws ClassNotFoundException {
        int tests = 0, passed = 0;

        Class testClass = Class.forName("annotation.Simple");
        for (Method m : testClass.getDeclaredMethods()) {
            if (m.isAnnotationPresent(Test.class)) {
                tests++;

                try {
                    m.invoke(null);
                    passed++;
                } catch (InvocationTargetException e) {
                    // 表示编译时没有捕获到 Test 注解 , 或者不可访问方法的注解

                    System.out.println(m  + " , failed: "  + e.getCause());

                } catch (Exception e) {
                    System.out.println("INVALID @Test : " + m);
                }
            }
        }

        System.out.println("tests: " + tests + ", passed:" + passed);
    }

//    新的注解类型类 测试
    public static void test2() throws ClassNotFoundException {
        int tests = 0, passed = 0;

        Class testClass = Class.forName("annotation.Simple2");
        for (Method m : testClass.getDeclaredMethods()) {
            if (m.isAnnotationPresent(Test.class)) {
                tests++;

                try {
                    m.invoke(null);
                    System.out.printf("Test  $s failed: no exception%n" , m);
                } catch (InvocationTargetException e) {
                    Throwable exc = e.getCause();
                    // 提取注解参数的值
                    Class<? extends Exception> excTypep =
                             m.getAnnotation(ExceptionTest.class).value();
                    // 判断: 抛出类型是注解的参数类型
                    if (excTypep.isInstance(exc)) {
                        passed++;
                    } else {
                        System.out.printf("Test $s failed; expected %s ; got %s%n",
                                m, excTypep.getName(), exc);
                    }

                } catch (Exception e) {
                    System.out.println("INVALID @Test : " + m);
                }
            }
        }

        System.out.println("tests: " + tests + ", passed:" + passed);
    }

}
